// 处理参数对象
const myParams = params => {
  let queryArr = []
  for (let key in params) {
    let query = key + '=' + params[key]
    queryArr.push(query)
  }
  return queryArr.join('&')
}

const myAjax = option => {
  //ajax函数返回一个Promise对象
  return new Promise((resolve, reject) => {
    // 创建xhr实例
    const xhr = new XMLHttpRequest()
    // 处理参数格式
    const query = myParams(option.data)
    // 设置响应格式
    xhr.responseType = 'json'
    // 判断并发送
    if (option.method.toUpperCase() === 'GET') {
      xhr.open('GET', query ? option.url + '?' + query : option.url)
      xhr.send()
    } else if (option.method.toUpperCase() === 'POST') {
      xhr.open('POST', option.url)
      // 设置请求头
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      xhr.send(query)
    }
    // 设置监听
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          resolve(xhr.response)
        } else {
          reject(xhr.status)
        }
      }
    }
  })
}